import codecs
import os
def write_list_to_file(data_list: list, path: str, is_append: bool = False):
    """
    要求data_list中每个元素(str)末尾没有换行, 该写入程序为每个item生成一个结尾的换行符
    :param data_list:
    :param path:
    :return:
    """
    os.makedirs(os.path.dirname(path), exist_ok=True)
    print("write_list_to_file()_数据总条数为:", len(data_list))
    with codecs.open(path, 'w' if not is_append else 'a', encoding='utf-8') as f:
        for data in data_list:
            f.write(data + '\n')


def load_list_file_clean(path: str):
    """
    得到不包含换行符的str_list
    :param path:
    :return:
    """
    if not os.path.exists(path):
        print(f'load_list_file_clean()_{path}文件不存在')
        return []

    with codecs.open(path, 'r', encoding='utf-8') as f:
        cat_to_name: list = f.read().splitlines()
        # cat_to_name: list = f.readlines() -> 包含换行符
        print(f"load_list_file_clean()_数据总条数为:{len(cat_to_name)}")
    return cat_to_name
def load_dict_from_tsv(input_tsv_path,is_relpath:bool=False):
    """"""
    print("load_dict_from_tsv", input_tsv_path)
    total_list = load_list_file_clean(input_tsv_path)
    root_dir = total_list[0]
    print("root_dir:", root_dir)
    left_list = total_list[1:]
    res_dict = {}
    for line in left_list:
        line_list = line.strip().split()
        assert len(line_list) == 2  # tsv的格式硬性要求
        if is_relpath:
            key = line_list[0]
        else:
            key = os.path.join(root_dir, line_list[0])
        res_dict[key] = line_list[1]
    return res_dict

def save_dict_to_tsv(input_dict, output_tsv_path):
    """
    将字典保存为tsv文件
    :param input_dict:
    :param output_tsv_path:
    :return:
    """
    res_list = ['/']
    for key, value in input_dict.items():
        res_list.append(key + '\t' + value)
    write_list_to_file(res_list, output_tsv_path)